package com.linciping.useges.plugin.asyc;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.linciping.useges.plugin.bean.File2R;
import com.linciping.useges.plugin.bean.PsiFile2Content;
import com.linciping.useges.plugin.bean.Res2SourceFile;
import com.linciping.useges.plugin.util.ProjectFileUtil;
import com.linciping.useges.plugin.util.Util;
import com.linciping.useges.plugin.writer.ModuleResUesgesWriter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class ModuleResUsegesThread extends ResUsegesThread {

    private final List<VirtualFile> findModuleFileList;

    public ModuleResUsegesThread(Project project, Module targetModule, List<File2R> resRList, List<VirtualFile> findModuleFileList) {
        super(project, targetModule, resRList);
        this.findModuleFileList = findModuleFileList;
    }

    @Override
    public void run() {
        try {
            List<Res2SourceFile> res2SourceFileList = new ArrayList<>();
            for (VirtualFile sourceFile : findModuleFileList) {
                final List<PsiFile2Content> waitFindPsiFileContentList = new ArrayList<>();
                buildSource(project, sourceFile, res2SourceFileList, waitFindPsiFileContentList);
            }
            final PsiDirectory moduleDirectory = ProjectFileUtil.getModuleDirectory(targetModule);
            if (moduleDirectory == null) return;
            ApplicationManager.getApplication().runWriteAction(() -> {
                CommandProcessor.getInstance().executeCommand(project, new ModuleResUesgesWriter(project, moduleDirectory, res2SourceFileList), "ResUesgesWriter", null);
            });
            callFinish();
        } finally {
            callFinish();
        }
    }

    @Override
    protected List<Res2SourceFile> executorFind(List<List<File2R>> file2RPool, List<PsiFile2Content> waitFindPsiFileContentList) throws ExecutionException, InterruptedException {
        return Util.executorFind(file2RPool, waitFindPsiFileContentList);
    }
}
